package com.zl.smartmall.library.im;

import java.util.Observer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.zl.smartmall.library.listener.BaseListener;
import com.zl.smartmall.library.listener.MessageListener;
import com.zl.smartmall.library.util.Constants;

import android.content.Context;
import android.content.Intent;
import android.util.SparseArray;

/**
 * 即时通信接口类<p>
 * 所有通信功能都可以通过此接口处理
 * @author 陈希然
 *
 */
public class IM {
	
	private static IM mInstance;
	private static Lock mLock;
	private Context mContext;
	private SparseArray<BaseListener> mSendListenerQueue;
	
	static{
		mLock = new ReentrantLock();
	}
	
	private IM(Context context) {
		IMWorker.init(context);
		mContext = context;
		mSendListenerQueue = new SparseArray<BaseListener>();
	}
	
	public static IM getInstance() {
		return mInstance;
	}
	
	public static void init(Context context) {
		if(mInstance == null){
    		mLock.lock();
    		try{
				if(mInstance == null){
					mInstance = new IM(context);
				}
    		}finally{
    			mLock.unlock();
    		}
    	}
	}
	
	/**
	 * 注册一个观测者, 成功注册后将自动接收IM新消息
	 * @param type 观测者类型
	 * @param observer 观测者
	 */
	public void registerObserver(int type, Observer observer) {
		IMWorker.getInstance().registerObserver(type, observer);
	}
	
	/**
	 * 注销一个观测者, 成功注销后将不再接收IM新消息
	 * @param type 观测者类型
	 * @param observer 观测者
	 */
	public void unRegisterObserver(int type, Observer observer) {
		IMWorker.getInstance().unRegisterObserver(type, observer);
	}
	
	/**
	 * 接收聊天消息
	 * @param chatId 聊天id
	 * @param msgId 消息id
	 */
	public void receiveMessage(int chatId, int msgId, MessageListener sendMessageListener) {
		Intent intent = new Intent(Constants.ACTION_RECEIVE_IM_MESSAGE);
		intent.putExtra("chatId", chatId);
		intent.putExtra("msgId", msgId);
		mContext.startService(intent);
	}
	
	/**
	 * 发送文本消息
	 * @param message 消息
	 * @param toUid 接收者id
	 */
	public void sendTextMessage(String message, int toUid, MessageListener sendMessageListener) {
//		RequestParams params = new RequestParams();
//		params.put("fuid", toUid);
//		params.put("content", message);
//		SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
//		SingtonAsyncHttpClient.getInstance().post(Constants.URL_SEND_IM_MESSAGE, params, sendMessageListener);
		
		putListener(toUid, sendMessageListener);
		
		Intent intent = new Intent(Constants.ACTION_SEND_IM_TEXT_MESSAGE);
		intent.putExtra("message", message);
		intent.putExtra("toUid", toUid);
		intent.putExtra("queueId", toUid);
		mContext.startService(intent);
	}
	
	private void putListener(int queueId, BaseListener listener) {
		mSendListenerQueue.put(queueId, listener);
	}
	
	public BaseListener obtainListener(int queueId) {
		return mSendListenerQueue.get(queueId);
	}
	
	public void removeListener(int queueId) {
		mSendListenerQueue.delete(queueId);
	}
}
